// 防抖
export function debounce(fn, delay = 300) {
  let timer;
  return function() {
    let that = this;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function() {
      fn.apply(that, arguments);
    }, delay);
  }
}

export function debounce2(fn, delay = 300) {
  let timer;
  return function() {
    let that = this;
    if (timer) {
      clearTimeout(timer);
    }
    return new Promise((resolve, reject) => {
      timer = setTimeout(function() {
        fn.apply(that, arguments).then(res => resolve(res), rej => reject(rej));
      }, delay);
    })
  }
}

// 节流
export const throttle = (fn, gapTime) => {
  let lastTime;
  let nowTime;
  return function() {
    nowTime = Date.now();
    if (!lastTime || nowTime - lastTime > gapTime) {
      fn();
      lastTime = nowTime;
    }
  }
}



export const isColor = value => {
  const colorReg = /^#([a-fA-F0-9]){3}(([a-fA-F0-9]){3})?$/;
  const rgbaReg = /^[rR][gG][bB][aA]\(\s*((25[0-5]|2[0-4]\d|1?\d{1,2})\s*,\s*){3}\s*(\.|\d+\.)?\d+\s*\)$/;
  const rgbReg = /^[rR][gG][bB]\(\s*((25[0-5]|2[0-4]\d|1?\d{1,2})\s*,\s*){2}(25[0-5]|2[0-4]\d|1?\d{1,2})\s*\)$/;
  return colorReg.test(value) || rgbaReg.test(value) || rgbReg.test(value);
};
// 验证手机号码
export const isMobileNumber = mobile => {
  return /^1[3456789]\d{9}$/.test(typeof mobile === "string" ? mobile : mobile.toString());
};

//生成从minNum到maxNum的随机数
export const randomNum = (minNum, maxNum) => {
  return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
};

// 生成随机颜色
export const getRandomColor = () => {
  const rgb = [];
  for (let i = 0; i < 3; ++i) {
    let color = Math.floor(Math.random() * 256).toString(16);
    color = color.length === 1 ? "0" + color : color;
    rgb.push(color);
  }
  return "#" + rgb.join("");
};
// 数组去重复
export const unique = arr => {
  return Array.from(new Set(arr))
}

// 浮点去尾
export const float2int = float => {
  float = float.toString();
  let index = float.indexOf(".");
  if (index !== -1) {
    float = float.substring(0, index + 1);
  } else {
    float = float.substring(0);
  }
  return parseInt(float);
};

/**
 * 数组拆分
 * num 每一组的个数
 */
export const arraySplit = (array, num = 3) => {
  let result = [];
  for (let i = 0; i < array.length; i += num) {
    result.push(array.slice(i, i + num));
  }
  return result;
}
